var exec	= require('child_process').exec
    , fs		= require('fs')
    , path	= require('path');

function getDefaultConfig(){
    return {
        encoding:'utf8',
        timeout:0,
        maxBuffer:200 * 1024
    }

}
var execFun=function (commands, settings, callback) {
    if(!settings)
        settings=getDefaultConfig();
    // Create final command line
    if(typeof(commands)=="string")
        var finalCommand=commands;
    else
        var finalCommand = commands.join(" ");
    // Create the timeoutId for stop the timeout at the end the process
    var timeoutID = null;
    // Exec the command
    var process = exec(finalCommand, settings, function (error, stdout, stderr) {
        // Clear timeout if 'timeoutID' are setted
        if (timeoutID !== null) clearTimeout(timeoutID);
        // Call the callback function
        callback(error, stdout, stderr);
    });
    // Verify if the timeout are setting
    if (settings.timeout > 0) {
        // Set the timeout
        timeoutID = setTimeout(function () {
            process.kill();
        }, 100);
    }
}
module.exports.getDefaultConfig=getDefaultConfig;
/**
 * Exec the list of commands and call the callback function at the end of the process
 */
module.exports.execAsync=async function(cmd,setting){
    return new Promise(function(resolve,rejected){
        execFun(cmd,setting,function(error, stdout, stderr){
            resolve({error, stdout, stderr});
        })
    })
}
module.exports.exec = execFun;